<template>
  <div class="device-list">
    <div class="page-header">
      <h1>桥梁系统设备列表</h1>
      <div class="header-actions">
        <t-button theme="primary" @click="handleAdd">
          <template #icon><t-icon name="add" /></template>
          添加设备
        </t-button>
        <t-input
          v-model="searchText"
          placeholder="搜索设备"
          style="width: 200px; margin-left: 16px"
          clearable
        >
          <template #suffix-icon>
            <t-icon name="search" @click="onSearch" />
          </template>
        </t-input>
      </div>
    </div>

    <t-table
      :columns="columns"
      :data="filteredDevices"
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      bordered
      row-key="id"
    >
      <template #status="{ row }">
        <t-tag :theme="row.status === '正常' ? 'success' : 'danger'">
          {{ row.status }}
        </t-tag>
      </template>
      <template #op="{ row }">
        <t-space>
          <t-link theme="primary" hover="color" @click="handleEdit(row)">编辑</t-link>
          <t-link theme="danger" hover="color" @click="showDeleteConfirm(row)">删除</t-link>
        </t-space>
      </template>
    </t-table>

    <t-dialog
      v-model:visible="modalVisible"
      :title="modalTitle"
      :confirm-loading="confirmLoading"
      @confirm="handleModalOk"
    >
      <t-form
        ref="formRef"
        :data="formState"
        :rules="rules"
        :label-width="80"
      >
        <t-form-item label="设备名称" name="name">
          <t-input v-model="formState.name" />
        </t-form-item>
        <t-form-item label="设备类型" name="type">
          <t-select v-model="formState.type">
            <t-option value="传感器" label="传感器" />
            <t-option value="监控设备" label="监控设备" />
            <t-option value="控制器" label="控制器" />
          </t-select>
        </t-form-item>
        <t-form-item label="安装位置" name="location">
          <t-input v-model="formState.location" />
        </t-form-item>
        <t-form-item label="安装日期" name="installDate">
          <t-date-picker v-model="formState.installDate" style="width: 100%" />
        </t-form-item>
        <t-form-item label="设备状态" name="status">
          <t-select v-model="formState.status">
            <t-option value="正常" label="正常" />
            <t-option value="故障" label="故障" />
          </t-select>
        </t-form-item>
      </t-form>
    </t-dialog>

    <t-dialog
      v-model:visible="deleteConfirmVisible"
      header="确认删除"
      body="确定要删除这个设备吗?"
      @confirm="confirmDelete"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import dayjs from 'dayjs';

// 表格列定义
const columns = [
  {
    colKey: 'id',
    title: '设备ID',
    width: '100',
  },
  {
    colKey: 'name',
    title: '设备名称',
  },
  {
    colKey: 'type',
    title: '设备类型',
  },
  {
    colKey: 'location',
    title: '安装位置',
  },
  {
    colKey: 'installDate',
    title: '安装日期',
  },
  {
    colKey: 'status',
    title: '设备状态',
    cell: 'status',
  },
  {
    colKey: 'op',
    title: '操作',
    width: '150',
    cell: 'op',
  },
];

// 模拟数据
const devices = ref([
  {
    id: '1',
    name: '振动传感器A1',
    type: '传感器',
    location: '主桥北侧',
    installDate: '2023-05-15',
    status: '正常',
  },
  {
    id: '2',
    name: '位移传感器B2',
    type: '传感器',
    location: '主桥南侧',
    installDate: '2023-06-20',
    status: '正常',
  },
  {
    id: '3',
    name: '监控摄像头C1',
    type: '监控设备',
    location: '桥梁入口',
    installDate: '2023-04-10',
    status: '故障',
  },
  {
    id: '4',
    name: '控制器D1',
    type: '控制器',
    location: '控制室',
    installDate: '2023-03-05',
    status: '正常',
  },
]);

const loading = ref(false);
const searchText = ref('');
const modalVisible = ref(false);
const modalTitle = ref('添加设备');
const confirmLoading = ref(false);
const formRef = ref(null);
const currentId = ref(null);
const deleteConfirmVisible = ref(false);
const deviceToDelete = ref(null);

// 表单状态
const formState = reactive({
  name: '',
  type: '传感器',
  location: '',
  installDate: null,
  status: '正常',
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  location: [{ required: true, message: '请输入安装位置', trigger: 'blur' }],
  installDate: [{ required: true, message: '请选择安装日期', trigger: 'change' }],
  status: [{ required: true, message: '请选择设备状态', trigger: 'change' }],
};

// 根据搜索条件过滤设备
const filteredDevices = computed(() => {
  if (!searchText.value) {
    return devices.value;
  }
  return devices.value.filter(
    (device) =>
      device.name.includes(searchText.value) ||
      device.type.includes(searchText.value) ||
      device.location.includes(searchText.value)
  );
});

// 搜索处理
const onSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

// 添加设备
const handleAdd = () => {
  resetForm();
  modalTitle.value = '添加设备';
  modalVisible.value = true;
  currentId.value = null;
};

// 编辑设备
const handleEdit = (row) => {
  modalTitle.value = '编辑设备';
  modalVisible.value = true;
  currentId.value = row.id;
  
  // 填充表单数据
  formState.name = row.name;
  formState.type = row.type;
  formState.location = row.location;
  formState.installDate = dayjs(row.installDate).toDate();
  formState.status = row.status;
};

// 显示删除确认对话框
const showDeleteConfirm = (row) => {
  deviceToDelete.value = row;
  deleteConfirmVisible.value = true;
};

// 确认删除设备
const confirmDelete = () => {
  if (deviceToDelete.value) {
    devices.value = devices.value.filter(item => item.id !== deviceToDelete.value.id);
    MessagePlugin.success('设备已删除');
    deviceToDelete.value = null;
  }
};

// 模态框确认
const handleModalOk = () => {
  formRef.value.validate().then((result) => {
    if (result === true) {
      confirmLoading.value = true;
      
      setTimeout(() => {
        if (currentId.value) {
          // 更新设备
          const index = devices.value.findIndex(item => item.id === currentId.value);
          if (index !== -1) {
            devices.value[index] = {
              ...devices.value[index],
              name: formState.name,
              type: formState.type,
              location: formState.location,
              installDate: dayjs(formState.installDate).format('YYYY-MM-DD'),
              status: formState.status,
            };
            MessagePlugin.success('设备已更新');
          }
        } else {
          // 添加设备
          const newId = (Math.max(...devices.value.map(d => parseInt(d.id))) + 1).toString();
          devices.value.push({
            id: newId,
            name: formState.name,
            type: formState.type,
            location: formState.location,
            installDate: dayjs(formState.installDate).format('YYYY-MM-DD'),
            status: formState.status,
          });
          MessagePlugin.success('设备已添加');
        }
        
        modalVisible.value = false;
        confirmLoading.value = false;
      }, 500);
    }
  }).catch(error => {
    console.log('验证失败:', error);
  });
};

// 重置表单
const resetForm = () => {
  formState.name = '';
  formState.type = '传感器';
  formState.location = '';
  formState.installDate = null;
  formState.status = '正常';
  
  // 重置表单验证状态
  if (formRef.value) {
    formRef.value.reset();
  }
};

// 生命周期钩子
onMounted(() => {
  // 这里可以添加从API获取设备列表的逻辑
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 500);
});
</script>

<style scoped>
.device-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}
</style> 